package nl.altenpts.net.kad;

import java.util.List;

import nl.altenpts.net.NetReactor;
import nl.altenpts.net.broker.IncomingMessage;
import nl.altenpts.net.broker.ResponseHandler;

public class StoreOperation extends Operation {

	public StoreOperation(List<Node> nodes, Value value, NetReactor reactor, Callback callback, KBroker broker) {
		super(nodes, Kademlia.keyToId(value.getKey()), reactor, callback);
		
		this.broker = broker;
		this.value = value;
	}

	@Override
	protected void sendRequest(Node node) {
		if(node != null) {
			broker.StoreRequest(node, value, new StoreResponseHandler(node));
		} else {
			finish();
		}
	}
	
	private class StoreResponseHandler implements ResponseHandler {
		
		public StoreResponseHandler(Node n) {
			node = n;
		}

		public void onResponse(IncomingMessage response) {
			nodeResponded(node, STATE_ANSWERED);
		}

		public void onTimeout() {
			nodeResponded(node, STATE_TIMEDOUT);			
		}
		
		private Node node;
	}
	
	private Value value;
	private KBroker broker;

}
